package helloRoom;

import com.alibaba.fastjson.JSON;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

import java.util.HashMap;

/**
 * Created by yunqisong on 2017/08/31.
 */
public class RoomServerHandler extends RoomAbsHandler implements ServerAioHandler {

    private static HashMap<String, ChannelContext> roomer = null;


    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        if (roomer == null) roomer = new HashMap<String, ChannelContext>();
        RoomPacket helloPacket = (RoomPacket) packet;
        byte[] body = helloPacket.getBody();
        if (body != null) {
            String str = new String(body, RoomConst.CHARSET);
            RoomAgreement agreement = JSON.parseObject(str, RoomAgreement.class);
            if (agreement != null) {
                if (!roomer.containsKey(agreement.getMe())) { // 是否包含当前上下文对象
                    roomer.put(agreement.getMe(), channelContext);
                }
                RoomPacket resppacket = new RoomPacket();
                ChannelContext to = roomer.get(agreement.getTo());
                if (to == null) {
                    to = channelContext;
                    resppacket.setBody(("您的好友-" + agreement.getTo() + " 尚未登录").getBytes(RoomConst.CHARSET));
                } else {
                    resppacket.setBody(("您的好友-" + agreement.getMe() + "说:" + agreement.getMsg()).getBytes(RoomConst.CHARSET));
                }
                Aio.send(to, resppacket);
                return;
            }
        }
        throw new RuntimeException("运行过程出现异常!");
    }
}
